﻿// var html = document.body.innerHTML;
// alert(html);

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
    var imgUrl = "";
    var cbuUrl = [];
    var detailsUrl = [];
    var error = 0;
    $("#dt-tab").find('img').each(function (){
        imgUrl = $(this).attr('src');
        imgUrl = imgUrl.replace('.60x60', '');
        imgUrl = imgUrl.replace('_.webp', '');
        if(imgUrl === 'https://cbu01.alicdn.com/cms/upload/other/lazyload.png'){
            alert('有橱窗图没有加载，请先加载！！');
            error = 1;
            return false;
        }
        cbuUrl.push(imgUrl);
    });
    if(error === 1){
        return false;
    };
    $("#mod-detail-description").find('img').each(function (){
        imgUrl = $(this).attr('src');
        if(imgUrl.substring(0,2) === '//'){
            alert('有详情图没有加载，请先加载！！');
            error = 1;
            return false;
        }
        detailsUrl.push(imgUrl);
    });
    if(error === 1){
        return false;
    };
    var fileName = window.prompt('请输入文件名（不输入也可以）', '');
    for(var i in cbuUrl){
        (function (t) {   // 注意这里是形参
            setTimeout(function () {
                downloadIamge(cbuUrl[t],fileName + '-' +  '橱窗图' + t)
            }, 500 * t);
        })(i)
    }
    for(var b in detailsUrl){
        (function (y) {   // 注意这里是形参
            setTimeout(function () {
                downloadIamge(detailsUrl[y],fileName + '-' +  '详情图' + y)
            }, 500 * i + 500 * y);
        })(b)
    }
});


function downloadIamge(imgsrc, name) {//下载图片地址和图片名
    let image = new Image();
    // 解决跨域 Canvas 污染问题
    image.setAttribute("crossOrigin", "anonymous");
    image.onload = function() {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
    };
    image.src = imgsrc;
}